package com.lightsh.graphics;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Log;

public class Sprite extends ChangeableDrawable{
	
	private Bitmap[] mBitmaps;
	private int mFrameIndex;
	private int mFrameW;
	private int mFrameH;
	private int mFrameCount;
	
	private Rect mSrc;
	private RectF mDst;
	/**
	 * 列数
	 */
	private int mCol;
	/**
	 * 行数
	 */
	private int mRow;

	public Sprite(Bitmap[] bitmaps, int nextFrameDelay){
		super(nextFrameDelay);
		if(mBitmaps == null || mBitmaps.length <= 0){
			throw new IllegalArgumentException("bitmaps length cant least than 2!");
		}
		mBitmaps = bitmaps;
		mFrameCount = mBitmaps.length;
		mFrameIndex = 0;
	}
	
	/**
	 * 将一张大图切分为多帧动画，注意，bitmap的高宽必须分别能整除frameW/frameH。
	 * @param bitmap
	 * @param frameW
	 * @param frameH
	 * @param nextFrameDelay
	 */
	public Sprite(Bitmap bitmap, int frameW, int frameH, int nextFrameDelay){
		super(nextFrameDelay);
		if(bitmap.getWidth() % frameW != 0 || bitmap.getHeight() % frameH != 0){
			throw new IllegalArgumentException("bitmap must be divisible by frameW and frameH!");
		}
		
		mBitmaps = new Bitmap[1];
		mBitmaps[0] = bitmap;		
		mFrameW = frameW;
		mFrameH = frameH;
		mFrameCount = (bitmap.getWidth() / frameW) * (bitmap.getHeight() / frameH);
		mFrameIndex = 0;
		mSrc = new Rect();
		mDst = new RectF();
		
		mRow = bitmap.getHeight() / frameH;
		mCol = bitmap.getWidth() / frameW;
	}
	
	@Override
	protected void nextFrame() {
		if(mFrameIndex == mFrameCount - 1){
			mFrameIndex = 0;
		}else{
			mFrameIndex++;
		}
	}

	@Override
	public void draw(Canvas canvas, Paint paint, int startX, int startY, float worldScale) {
		
		int index = 0;		
		mDst.left = startX * worldScale;
		mDst.top = startY * worldScale;
		
		if(mBitmaps.length == 1){
			int rowIndex = mFrameIndex / mCol;
			int colIndex = mFrameIndex % mCol;
			
			mSrc.left = colIndex * mFrameW;
			mSrc.right = mSrc.left + mFrameW;			
			mSrc.top = rowIndex * mFrameH;
			mSrc.bottom = mSrc.top + mFrameH;
			
			mDst.right = mDst.left + mFrameW * worldScale;
			mDst.bottom = mDst.top + mFrameH * worldScale;
		}else{
			index = mFrameIndex;
			
			final int bitmapW = mBitmaps[mFrameIndex].getWidth();
			final int bitmapH = mBitmaps[mFrameIndex].getHeight();;
			mSrc.left = 0;
			mSrc.top = 0;
			mSrc.right = bitmapW;
			mSrc.bottom = bitmapH;
			
			mDst.right = mDst.left + bitmapW * worldScale;
			mDst.bottom = mDst.top + bitmapH * worldScale;
		}
		
		canvas.drawBitmap(mBitmaps[index], mSrc, mDst, paint);
		
	}

}
